﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;


namespace CCPSIP.Robot
{
    /// <summary>機器人服務: 取得選項列表</summary>

    public class option_list : IHttpHandler
    {
        private const int kRespMaxKB = 300;//in KB

        private static Dictionary<string, string> kServiceDicts = new Dictionary<string, string>()
    {
      { "RobotLeaveRun", "http://ios.ccp.com.tw/Fado/IOS_KIOSK_Webservice/iSender_ListQuery.ashx" },
      { "RobotBizTrip", "http://ios.ccp.com.tw/Fado/IOS_KIOSK_Webservice/iSender_ListQuery.ashx" },
      { "RobotOvertime", "http://ios.ccp.com.tw/Fado/IOS_KIOSK_Webservice/iSender_ListQuery.ashx" },
      { "RobotDebug", "http://ios.ccp.com.tw/Fado/IOS_KIOSK_Webservice/iSender_ListQuery.ashx" }
    };


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ROBOT_ID = req.Form["ROBOT_ID"];
                string QUERY_KIND = req.Form["QUERY_KIND"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查 ROBOT_ID
                //
                if (!kServiceDicts.ContainsKey(ROBOT_ID))
                {
                    throw new Exception("Error_02: Service not found");//找不到此服務
                }


                //【03】呼叫 Web Service: 發出 Request
                //
                string SYSTEM_KIND = ROBOT_ID;
                string ServiceURL = kServiceDicts[ROBOT_ID];

                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(ServiceURL);
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                webReq.ProtocolVersion = HttpVersion.Version11;
                webReq.Method = "POST";
                webReq.Timeout = 60 * 1000;
                webReq.KeepAlive = false;
                webReq.AllowAutoRedirect = false;
                webReq.Proxy = new WebProxy();
                webReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

                Dictionary<string, string> paramDict = new Dictionary<string, string>();
                paramDict["SIP_NUM"] = userInfo.SIP_Num;
                paramDict["PPS_CODE"] = Convert.ToString(userInfo.PPS_CODE);
                paramDict["SYSTEM_KIND"] = SYSTEM_KIND;
                paramDict["QUERY_KIND"] = QUERY_KIND;
                string paramStr = ChrisKit.DictToQueryStr(paramDict, encoding);

                byte[] postBytes = encoding.GetBytes(paramStr);
                webReq.ContentLength = postBytes.Length;
                using (System.IO.Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                    reqStream.Flush();
                    reqStream.Close();
                }


                //【04】呼叫 Web Service: 接收 Response
                //
                HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
                System.IO.Stream respStream = webResp.GetResponseStream();
                byte[] respBytes = new byte[kRespMaxKB * 1024];
                int bytesCount = 0;

                for (int i = 0; i < kRespMaxKB; i++)
                {
                    int readCount = respStream.Read(respBytes, bytesCount, 1024);
                    if (readCount == 0)
                        break;
                    else
                        bytesCount += readCount;
                }
                respStream.Close();
                webResp.Close();


                //【05】檢查回傳格式
                //
                string respStr = encoding.GetString(respBytes, 0, bytesCount);

                if (Regex.IsMatch(webResp.ContentType, "^application/json"))
                {
                    //【98】正常: 以JSON格式回傳
                    //
                    resp.ContentType = "application/json";
                    resp.Charset = null;
                    fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                    resultStr = respStr;

                    //【98-1】特殊字串替換
                    resultStr = resultStr.Replace("Name\":\"籃聖", "Name\":\"籃聖喆 Chuck");
                    resultStr = resultStr.Replace("Name\":\"陳虹", "Name\":\"陳虹伃");
                }
                else if (Regex.IsMatch(webResp.ContentType, "^(application|text)/xml"))
                {
                    //【99】異常: 以XML格式回傳
                    //
                    resp.ContentType = "application/xml";
                    resultStr = respStr;
                }
                else
                {
                    //非預期的回應
                    string errorMsg = string.Format("Error_11: Unexpected Response ({0})", webResp.ContentType);
                    throw new Exception(errorMsg);
                }
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
